(function(window){
    
    window.C = {};

    //绑定事件，兼容 ie
    function bindEvent(obj, event, fn){
        if(obj.attachEvent){
            obj.attachEvent('on'+event, function () {
                fn.call(obj);
            })
        }else{
            obj.addEventListener(event, fn, false);
        }
    }

    //获取鼠标 x y 坐标
    C.getPos = function(dom){
        var oPos = {x:0, y:0};
        
        bindEvent(dom, 'mousemove', function (ev) {

            var oEvent = ev || event, x, y;
            if(oEvent.pageX || oEvent.pageY){
                x = oEvent.pageX;
                y = oEvent.pageY;
            }else{
                x = oEvent.clientX + document.body.scrollLeft || document.documentElement.scrollLeft;
                y = oEvent.clientY + document.body.scrollTop || document.documentElement.scrollTop;
            }
            x-=dom.offsetLeft;
            y-=dom.offsetTop;
            oPos.x = x;
            oPos.y = y;
        });
        return oPos;
    }

    //获取随机 rgb 颜色
    C.getRandomColor = function () {
        var r = Math.floor(Math.random() * 256);
        var g = Math.floor(Math.random() * 256);
        var b = Math.floor(Math.random() * 256);
        return "rgb(" + r + "," + g + "," + b + ")";
    }

    //图形化验证码
    C.validatePic = function (dom) {

        if(!dom || !dom instanceof HTMLElement){
            throw '您传入的参数不是 dom 元素节点';
            return false;
        }

        var width = dom.clientWidth,
            height = dom.clientHeight,
            vc = document.createElement('canvas'),
            ctx = vc.getContext('2d'),
            chars = ['a','b','c','d','e','f','g','h','i','j','k','m','n','p','q','r','s','t','u','v','w','x','y','z',
                      'A','B','C','D','E','F','G','H','J','K','L','M','N','P','Q','R','S','T','U','V','W','X','Y','Z',
                      '0','2','3','4','5','6','7','8','9'],
            totalNum = 4,         //字符数量
            interfereNum = 10,    //干扰线条数量
            pointNum = 100,       //干扰点数量
            vStr = "";            //验证码字符串

        vc.innerText = "您的浏览器可能不支持 canvas";
        vc.width = width;
        vc.height = height;
        dom.appendChild(vc);

        //干扰线条
        for(var idx=0;idx<interfereNum;idx++){
            ctx.beginPath();
            ctx.strokeStyle = C.getRandomColor();
            ctx.moveTo(Math.random()*width, Math.random()*height);
            ctx.lineTo(Math.random()*width, Math.random()*width);
            ctx.closePath();
            ctx.stroke();
        }

        //干扰点
        for(var idx=0;idx<pointNum;idx++){
            var ix = Math.random()*width,
                iy = Math.random()*height;
            ctx.beginPath();
            ctx.strokeStyle = C.getRandomColor();
            ctx.moveTo(ix, iy);
            ctx.lineTo(ix+1, iy+1);
            ctx.closePath();
            ctx.stroke();
        }

        //验证码
        for(var idx=0;idx<totalNum;idx++){
            var str = chars[Math.floor(Math.random()*chars.length)],
                deg = Math.random() * 45 * Math.PI / 180,//产生0~30之间的随机弧度
                x = 0,
                y = 0;
                vStr += str;

            //字的坐标
            x = 8+idx*20;
            y = height/2 + Math.random()*8;

            ctx.beginPath();
            ctx.translate(x,y);
            ctx.rotate(deg);
            ctx.font = "bolder 24px 微软雅黑";
            ctx.fillStyle = C.getRandomColor();
            ctx.fillText(str, 0, 0);
            ctx.closePath();

            ctx.rotate(-deg);
            ctx.translate(-x, -y);
        }

        return vStr;
    }

    //图形化滑块验证码
    C.validateSliderPic = function (dom, imgPath) {
        if(!dom || !dom instanceof HTMLElement){
            throw '您传入的参数不是 dom 元素节点';
            return false;
        }

        var width = dom.clientWidth,
            height = dom.clientHeight,
            canvas = document.createElement("canvas"),
            ctx = canvas.getContext("2d"),
            sCanvas = document.createElement("canvas"),
            sCtx = sCanvas.getContext("2d");

        canvas.width = width;
        canvas.height = height;
        canvas.innerText = "您的浏览器可能不支持 canvas";

        sCanvas.width = width;
        sCanvas.height = height;
        sCanvas.innerText = "您的浏览器可能不支持 canvas";

        dom.appendChild(canvas);
        dom.appendChild(sCanvas);

        var rectX = 120, rectY = 50, rectW = 50, rectH = 50, arcR = 10, PI = Math.PI;

        var img = new Image();
        img.src = imgPath;
        img.onload = function () {
            ctx.drawImage(img,0,0,width,height);
            sCtx.drawImage(img,0,0,width,height);

            var cw = rectW + arcR*2;
            var cy = rectY - arcR*2;
            var imgData = sCtx.getImageData(rectX,cy,cw,cw);
            sCanvas.width = cw;
            sCtx.putImageData(imgData,0,cy);
        }

        function drawClip(c, operation){
            //矩形
            c.beginPath();
            c.moveTo(rectX,rectY);
            c.rect(rectX,rectY,rectW,rectH);

            //上圆
            c.moveTo(rectX+rectW/2,rectY-arcR);
            c.arc(rectX+rectW/2,rectY-arcR,arcR,0,360*PI/180,false);

            //右圆
            c.moveTo(rectX+rectW+arcR,rectY+rectH/2);
            c.arc(rectX+rectW+arcR,rectY+rectH/2,arcR,0,360*PI/180,false);
            c.closePath();
            c[operation]();

            //左圆
            c.beginPath();
            c.moveTo(rectX,rectY+rectH/2);
            c.arc(rectX+arcR,rectY+rectH/2,arcR,0,360*Math.PI/180,false);
            c.globalCompositeOperation = "xor";
            c.fill();
        }
        drawClip(ctx, "fill");
        drawClip(sCtx, "clip");
    }

    //刮刮卡
    C.lottery = function (dom) {

        if(!dom || !dom instanceof HTMLElement){
            throw '您传入的参数不是 dom 元素节点';
            return false;
        }

        var width = dom.clientWidth,
            height = dom.clientHeight,
            canvas = document.createElement("canvas"),
            ctx = canvas.getContext("2d");

        canvas.innerText = "您的浏览器可能不支持 canvas";
        canvas.width = width;
        canvas.height = height;
        dom.appendChild(canvas);

        //创建蒙层
        ctx.beginPath();
        ctx.fillStyle = "#9a9a9a";
        ctx.closePath();
        ctx.fillRect(0,0,width,height);

        //绑定刮卡事件(兼容移动端和 pc 端写法)
        var hastouch = "ontouchstart" in window ? true : false,
            tapstart = hastouch ? "touchstart" : "mousedown",
            tapmove = hastouch ? "touchmove" : "mousemove",
            tapend = hastouch ? "touchend" : "mouseup";

        var points = [],
            x,
            y,
            isDown = false;

        canvas.addEventListener(tapstart,function (e) {
            isDown = true;
            x = hastouch ? e.targetTouches[0].pageX : e.clientX - this.offsetLeft;
            y = hastouch ? e.targetTouches[0].pageY : e.clientY - this.offsetTop;
            points.push([x,y]);
            eraser(ctx);
        },false);

        canvas.addEventListener(tapmove,function (e) {
            if(!isDown){
                return false;
            }
            x = hastouch ? e.targetTouches[0].pageX : e.clientX - this.offsetLeft;
            y = hastouch ? e.targetTouches[0].pageY : e.clientY - this.offsetTop;
            points.push([x,y]);
            eraser(ctx);
        },false);

        canvas.addEventListener(tapend,function () {
            isDown = false;
            points = [];
        },false);

        function eraser(ctx){
            ctx.save();
            ctx.beginPath();
            ctx.moveTo(points[0][0], points[0][1]);
            ctx.lineCap = "round";
            ctx.lineJoin = "round";
            ctx.lineWidth = 30;
            ctx.globalCompositeOperation = "destination-out";
            if(points.length == 1){
                ctx.lineTo(points[0][0] + 1, points[0][1] + 1);
            }else{
                for(var idx=0;idx<points.length;idx++){
                    ctx.lineTo(points[idx][0], points[idx][1]);
                    ctx.moveTo(points[idx][0], points[idx][1]);
                }
            }
            ctx.closePath();
            ctx.stroke();
            ctx.restore();
        }

        //刮开面积的比例
        function proportion(ctx){
            var total = 0,
                count = 0,
                imgData,
                data;
            imgData = ctx.getImageData(0,0,width,height);
            data = imgData.data;
            for(var idx=0;idx<data.length;idx+=4){
                var a = data[idx+3];
                if(a == 0){
                    count += 1;
                }
                total += 1;
            }

            return count/total;
        }
    }

    //账号操作
    const accountFiledName = "ACCOUNT";
    const passwordFiledName = "PASSWORD";
    C.account = {
        save: function (account, password) {
            this.isCompatible();
            window.localStorage.setItem(accountFiledName, account);
            window.localStorage.setItem(passwordFiledName, password);
        },
        get: function () {
            this.isCompatible();
            var account = window.localStorage.getItem(accountFiledName) || null,
                password = window.localStorage.getItem(passwordFiledName) || null;

            return {account:account, password:password};
        },
        clear: function () {
            this.isCompatible();
            window.localStorage.removeItem(accountFiledName);
            window.localStorage.removeItem(passwordFiledName);
        },
        show: function(accountDom, passwordDom){

            this.isCompatible();
            accountDom.value = this.get().account;
            passwordDom.value = this.get().password;
        },
        isCompatible: function () {
            if(!window.localStorage){
                throw '您的浏览器不支持 localStorage';
                return false;
            }
        }
    }

})(window);